package com.by.wx.process.task;

import cn.hutool.core.collection.CollectionUtil;
import com.by.wx.mapper.MonitorTaskMapper;
import com.by.wx.model.script.CsTask;
import com.by.wx.model.script.MonitorTask;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 陈子杰
 * @Description 任务处理类
 * @Version 1.0.0
 * @Date 2025/2/16 3:15
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TaskProcessServ {
    private final MonitorTaskMapper monitorTaskMapper;

    /**
     * 获取需要处理的所有任务
     * @return {@link List }<{@link CsTask }>
     */
    public List<CsTask> getTasks() {
        // 获取当前未结束的任务
        List<MonitorTask> unfinishedTasks = monitorTaskMapper.getUnfinishedTasks();
        if (CollectionUtil.isEmpty(unfinishedTasks)) {
            return null;
        }
        // 任务分组,把同一航线同一日期同一航班的任务作为一个任务去处理
        Map<Long, List<MonitorTask>> groupMap = new HashMap<>();
        for (MonitorTask task : unfinishedTasks) {
            if (!groupMap.containsKey(task.getId())) {
                List<MonitorTask> groupList = new ArrayList<>();
                for (MonitorTask t : unfinishedTasks) {
                    if (MonitorTask.commonCabin(task, t)) {
                        groupList.add(t);
                    }
                }
                groupMap.put(task.getId(), groupList);
            }
        }
        List<CsTask> tasks = new ArrayList<>();
        for (Map.Entry<Long, List<MonitorTask>> taskEntry : groupMap.entrySet()) {
            List<MonitorTask> value = taskEntry.getValue();
            List<String> chatroomIds = value.stream().map(MonitorTask::getChatroomId).collect(Collectors.toList());
            MonitorTask monitorTask = value.get(0);
            CsTask task = CsTask.builder()
                    .userId(chatroomIds)
                    .flightNo(monitorTask.getFlightNo())
                    .date(monitorTask.getDate())
                    .departure(monitorTask.getDeparture())
                    .arrival(monitorTask.getArrival())
                    .cabin(monitorTask.getCabin())
                    .build();
            tasks.add(task);
        }
        return tasks;
    }
}
